<template>
  <el-card class="card" shadow="never">
    <el-input v-model="filterText" class="input" :placeholder="$t('message.dict.inputCatalog')" />
    <el-tree      
      ref="tree"
      :data="treeData"
      :props="defaultProps"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      :highlight-current="true"
      :default-expanded-keys="defaultExpandedKeys"
      node-key="id"
      @node-click="onFilter"
    >
      <template #default="{ node }">
        <div class="node">
          <span>{{ node.label }}</span>
          <div>
            <i class="el-icon-plus" size="small" @click.stop="onCreate(node.data)" />
            <i class="el-icon-minus" @click.stop="$emit('delete-node', node.data.id)" />
          </div>
        </div>
      </template>
    </el-tree>
  </el-card>
</template>

<script>
export default {
  props: {
    treeData: {
      type: Object,
      required: true,
    },
    addNode: {
      type: Function,
      required: true,
    },
    defaultExpandedKeys:{
      type: Array,
      required: false,
    }
  },
  emits: ['update:modelValue', 'on-search', 'delete-node'],
  data() {
    return {
      loading: false,
      filterText: null,
      defaultProps: {
        children: 'children',
        label: function(a){
          return a.dictName || a.name
        },
      },
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      if(data.dictName){
        return data.dictName.indexOf(value) !== -1
      }else{
        return data.name.indexOf(value) !== -1
      }
      
    },
    onFilter(data) {
      this.$emit('update:modelValue', data.id)
      this.$emit('on-search', data)      
    },
    onCreate({ id, dictName, name }) {
      const initValues = {
        parentId: id,
      }
      dictName = dictName || name
      this.addNode(initValues, dictName)
    },
  },
}
</script>
<style lang="scss" scoped>
.card {
  margin-right: 10px;
  height: calc(100vh - 150px);
  min-height: 360px;
  overflow-y: auto;
  border: 1px solid #e6ebf5;
  /deep/ .el-card{
    border: none;
  }
  &:deep(.el-tree-node__content) {
    height: 0;
    min-height: 26px;
    height: auto;
  }
  .border-none{
    border: none !important;
  }
  .input {
    margin-bottom: 10px;
  }
  .node {
    display: flex;
    width: 100%;
    span {
      font-size: 14px;
      margin-right: auto;
      color: #606266;
      white-space: normal;
      padding: 4px 0;
    }
    i {
      flex: 1;
      font-size: 12px;
      margin-left: 12px;
      color: #409eff;
    }
  }
}
// .el-tree{
//   width: 500px;
//   overflow-x: auto;
// }
</style>
